/**
 * 
 */
package com.shuqi.activity.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;

import com.shuqi.activity.FragmentActivityBase;
import com.shuqi.activity.Fragments.OfferWallGoodGameFragment;
import com.shuqi.activity.Fragments.OfferWallHotAppFragment;
import com.shuqi.common.Constant;

/**
 * 推广墙viewpager适配器
 * 
 * @author linyuren
 * 
 */
public class OfferWallTopAdapter extends FragmentPagerAdapter {

    private SparseArray<Fragment> map;

    public OfferWallTopAdapter(FragmentManager fm, FragmentActivityBase context) {
        super(fm);
        map = new SparseArray<Fragment>();
    }

    @Override
    public Fragment getItem(int position) {
        if (map.get(position) == null) {
            map.put(position, createItem(position));
        }
        return map.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = null;
        try {
            fragment = (Fragment) super.instantiateItem(container, position);
        } catch (Exception e) {
        }
        if (fragment == null) {
            fragment = createItem(position);
        }
        map.put(position, fragment);
        return fragment;
    }

    /**
     * 添加各子模块的Fragment
     * 
     * @param position
     * @return
     */
    private Fragment createItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case Constant.SLIDING_0:
                fragment = new OfferWallHotAppFragment();
                break;
            case Constant.SLIDING_1:
                fragment = new OfferWallGoodGameFragment();
                break;
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return null;
    }

    /**
     * 
     * @param position
     */
    public void notifyOnPageSelected(int position) {
        Fragment fragment = map.get(position);
        switch (position) {
            case Constant.SLIDING_0:
                if (fragment != null && fragment instanceof OfferWallHotAppFragment) {
                    ((OfferWallHotAppFragment) fragment).onPageSelected();
                }
                break;
            case Constant.SLIDING_1:
                if (fragment != null && fragment instanceof OfferWallGoodGameFragment) {
                    ((OfferWallGoodGameFragment) fragment).onPageSelected();
                }
                break;
        }
    }


}
